<!-- Datatables -->
<link href="cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css"/>
<link href="/vendors/datatables.net-bs/css/dataTables.bootstrap.min.css" rel="stylesheet"/>
<!-- page content -->
<div id="roles" class="right_col" role="main">
    <div class="">
        <div class="page-title">
            <div class="title_left">
                <h3>
                    Roles Page
                </h3>
            </div>
        </div>
        <div class="clearfix"></div>
        <div class="row">
            <div class="col-md-12 col-sm-12 ">
                <div class="x_panel">
                    <div class="x_title">
                        <button class="btn btn-primary"
                                data-toggle="modal"
                                data-target="#modalAdd"
                                @click="initAddModel()">新增
                        </button>
                        <ul class="nav navbar-right panel_toolbox">
                            <li><a class="collapse-link"><i class="fa fa-chevron-up"></i></a>
                            </li>
                            <li class="dropdown">
                                <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button"
                                   aria-expanded="false"><i class="fa fa-wrench"></i></a>
                                <div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
                                    <a class="dropdown-item" href="#">Settings 1</a>
                                    <a class="dropdown-item" href="#">Settings 2</a>
                                </div>
                            </li>
                            <li><a class="close-link"><i class="fa fa-close"></i></a>
                            </li>
                        </ul>
                        <div class="clearfix"></div>
                    </div>
                    <div class="x_content">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="card-box table-responsive">
                                    <table id="dataTable"
                                           class="table table-striped table-bordered"
                                           style="width:100%">
                                        <thead>
                                        <tr>
                                            <th>Id</th>
                                            <th>Role Name</th>
                                            <th>Create Date</th>
                                            <th>Operate</th>
                                        </tr>
                                        </thead>
                                        <tbody>
                                        </tbody>
                                    </table>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div th:replace="account/roleAdd"></div>
    <div th:replace="account/roleEdit"></div>
</div>
<!-- Datatables -->
<script src="/vendors/datatables.net/js/jquery.dataTables.min.js"></script>
<script src="/vendors/datatables.net-bs/js/dataTables.bootstrap.min.js"></script>
<!-- /page content -->
<script>
    var rolesVue = new Vue({
        el: "#roles",
        data: {
            // 初始化分页页长
            pageSize: 5,
            // 定义表格数据结构
            tableData: {
                draw: 0,
                recordsTotal: 0,
                recordsFiltered: 0,
                data: [],
            },
            role: {
                id: "",
                roleName: "",
                createDate: "",
            },
        },
        methods: {
            // 定义 表格行 数据结构
            rowData: function (id, roleName, createDate) {
                var row = {};
                row.id = id;
                row.roleName = roleName;
                row.createDate = createDate;
                row.operate = function () {
                    return (
                        "<a href='#' class='btn_editcolor' data-toggle='modal' " +
                        "data-target='#modalEdit' onclick='initEditModel(\"" + id +
                        "\")'>编辑</a>&nbsp;" +
                        "<a href='javascript:void(0);' onclick='deleteModel(\"" +
                        id +
                        "\")' class='btn_editcolor'>删除</a>"
                    );
                };
                return row;
            },
            // 初始化表格
            initTable: function () {
                var self = this;
                $("#dataTable").DataTable({
                    paging: true, //分页
                    serverSide: true, //开启后端分页
                    pagingType: "full_numbers", //分页样式的类型simple/simple_numbers/full/full_numbers
                    pageLength: this.pageSize, //定义初始的页长
                    processing: true,
                    destroy: true, //允许销毁替换，在表格重新查询时，可以自动销毁以前的data
                    lengthChange: true, //控制是否能够调整每页的条数
                    searching: true,    //搜索
                    "data-show-refresh": true,  //数据显示 刷新
                    ordering: true,     // 排序
                    autoWidth: false,   // 宽度自动化
                    ajax: function (data, callback, settings) {
                        // 从 data 中获取查询数据
                        var columIndex = data.order[0].column;
                        var direction = data.order[0].dir;
                        var orderBy = data.columns[columIndex].name;
                        pageSize = data.length == undefined ? pageSize : data.length;

                        var searchBean = {};
                        searchBean.currentPage = data.start / pageSize + 1;
                        searchBean.pageSize = pageSize;
                        searchBean.orderBy = orderBy;
                        searchBean.direction = direction;
                        searchBean.keyword = data.search.value;
                        console.log(searchBean);
                        $.ajax({
                            url: "/api/roles",
                            type: "post",
                            contentType: "application/json",
                            data: JSON.stringify(searchBean),
                            success: function (rs) {
                                if (!rs) {
                                    layer.alert("请求出错，请稍后重试" + rs.errmsg, {icon: 2});
                                    callback(self.tableData);
                                    return;
                                }
                                if (rs.list == null) {
                                    callback(self.tableData);
                                    return;
                                }

                                var rowsData = [];
                                for (var i = 0; i < rs.list.length; i++) {
                                    //包装 行 数据
                                    var rowData = self.rowData(
                                        rs.list[i].id,
                                        rs.list[i].roleName,
                                        rs.list[i].createDate,
                                    );

                                    // 将 行 数据放到数组里
                                    rowsData.push(rowData);
                                }
                                self.tableData.data = rowsData;
                                self.tableData.recordsTotal = rs.total;
                                self.tableData.recordsFiltered = rs.total;
                                callback(self.tableData);
                            },
                        });
                    },
                    columns: [
                        //定义 行 数据字段
                        {data: "id", name: "id", sortable: true},
                        {data: "roleName", name: "role_name", sortable: true},
                        {data: "createDate", name: "create_date", sortable: true},
                        {data: "operate", width: "80px", sortable: false},
                    ],
                });
            },

            // 每次进入新增 模态框内都清除上一次残留的数据
            initAddModel: function () {
                this.role = {
                    id: "",
                    roleName: "",
                    createDate: "",
                };
            },
            // 向 role 、role_role 表中新增数据
            insertModel: function () {
                if ( this.role.roleName == "" ){
                    layer.alert("Please input role info.", { icon: 0});
                    return;
                }

                var self = this;
                $.ajax({
                    url: "/api/role",
                    type: "post",
                    contentType: "application/json",
                    data: JSON.stringify(self.role),
                    success: function (rs) {
                        if (rs.status == 200) {
                            // 关闭模态框
                            $("#modalAdd").modal("hide");
                            // 刷新表格
                            self.initTable();
                        } else {
                            layer.alert(rs.message, { icon: 0 });
                        }
                    },
                    error: function (data) {
                        layer.alert(data.responseText, { icon: 0 });
                    },
                });
            },
            // 点击 编辑选项 后显示所在行的可修改数据
            initEditModel: function (id) {
                var self = this;
                $.ajax({
                    url: "/api/role/" + id,
                    type: "get",
                    success: function (rs) {
                        self.role = rs;
                    },
                    error: function (data) {
                        layer.alert(data.responseText, { icon: 0 });
                    },
                });
            },

            // 点击 Save Changes 进行修改
            updateModel: function () {
                if ( this.role.roleName == "" ){
                    layer.alert("Please input role info.", { icon: 0});
                    return;
                }
                var self = this;
                $.ajax({
                    url: "/api/role",
                    type: "put",
                    contentType: "application/json",
                    data: JSON.stringify(self.role),
                    success: function (rs) {
                        if (rs.status == 200) {
                            // 关闭模态框
                            $("#modalEdit").modal("hide");
                            // 刷新表格
                            self.initTable();
                        } else {
                            layer.alert(rs.message, { icon: 0 });
                        }
                    },
                    error: function (data) {
                        layer.alert(data.responseText, { icon: 0 });
                    },
                });
            },
            deleteModel: function (id) {
                var self = this;
                bootbox.confirm("Are you sure you want to delete it?", function (result) {
                    if (result) {
                        $.ajax({
                            url: "/api/role/" + id,
                            type: "delete",
                            success: function (rs) {
                                if (rs.status == 200){
                                    self.initTable();
                                }else {
                                    layer.alert(rs.message, { icon: 0 });
                                }
                            },
                            error: function (data) {
                                layer.alert(data.responseText, { icon: 0 });
                            }
                        });
                    }
                });
            },
        },
        created: function () {
          window.initEditModel = this.initEditModel;
          window.deleteModel = this.deleteModel;
        },
        mounted: function () {
            this.initTable();
        },
    });
</script>